package top.hcode.hoj.service.admin;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import top.hcode.hoj.dao.course.StuffDao;
import top.hcode.hoj.pojo.dto.QueryStuffDTO;
import top.hcode.hoj.pojo.dto.SaveStuffDto;
import top.hcode.hoj.pojo.entity.course.Stuff;
import top.hcode.hoj.pojo.vo.StuffTypeCountVO;
import top.hcode.hoj.pojo.vo.StuffVO;
import top.hcode.hoj.utils.AliyunOSSUtils;
import top.hcode.hoj.utils.HttpUtils;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author orangej
 * @since 2024/12/31
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AdminStuffService {
    private final StuffDao stuffDao;

    public IPage<StuffVO> queryList(QueryStuffDTO dto) {
        IPage<StuffVO> pager = stuffDao.adminQuery(dto);
        return pager;
    }

    @Transactional
    public void saveStuff(SaveStuffDto dto) {
        if ("md".equalsIgnoreCase(dto.getStuffType())) {
            saveMdContent(dto);
        }
        stuffDao.saveOrUpdate(dto);
    }

    private void saveMdContent(SaveStuffDto dto) {
        String content = dto.getContent();
        String fileUrl = dto.getFileUrl();
        if (dto.getId() == null && Strings.isNotBlank(fileUrl) && Strings.isBlank(content)) {
            // 文件上传md
            return;
        }

        Validator.validateNotEmpty(content, "内容不能为空");

        byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8);
        dto.setFileSize(contentBytes.length);
        if (Strings.isBlank(fileUrl)) {
            // 上传md文件
            fileUrl = AliyunOSSUtils.uploadFileWithSuffix(contentBytes, "md");
            dto.setContent(fileUrl);
        } else {
            // 更新md
            String key = StrUtil.removePrefix(URLUtil.getPath(fileUrl), "/");
            AliyunOSSUtils.deleteFile(key);
            AliyunOSSUtils.uploadFile(contentBytes, key);
        }

        dto.setFileUrl(fileUrl);
    }

    @Transactional
    public void deleteStuff(List<String> idList) {
        if (idList.isEmpty()) return;

        // remove children
        stuffDao.removeChildrenOf(idList);

        stuffDao.removeByIds(idList);
    }

    public List<StuffTypeCountVO> queryTypeCount(QueryStuffDTO dto) {
        return stuffDao.queryTypeCount(dto);
    }

    public StuffVO getStuffDetail(Long id) {
        Stuff stuff = stuffDao.getById(id);
        StuffVO vo = new StuffVO();
        Lang.copyProperties(stuff, vo);

        if (vo.getStuffType().equalsIgnoreCase("md")) {
            String content = HttpUtils.downloadFileContent(vo.getFileUrl());
            vo.setContent(content);
        }

        return vo;
    }
}
